/**
 * 请求工具辅助函数
 */

import type {UniRequestConfig, UniRequestError, UniRequestInternalConfig} from './types'

/**
 * 合并配置对象
 * @param target 目标配置
 * @param source 源配置
 * @returns 合并后的配置
 */
export function mergeConfig(target: Partial<UniRequestConfig>, source: UniRequestConfig): UniRequestInternalConfig {
    const merged: UniRequestConfig = {...target} as UniRequestConfig;

    Object.keys(source).forEach(key => {
        const sourceValue = source[key as keyof UniRequestConfig]
        const targetValue = merged[key as keyof UniRequestConfig]

        if (key === 'headers' && targetValue && sourceValue) {
            // 合并请求头
            merged.headers = {...targetValue as Record<string, string>, ...sourceValue as Record<string, string>}
        } else if (key === 'params' && targetValue && sourceValue) {
            // 合并URL参数
            merged.params = {...targetValue as Record<string, any>, ...sourceValue as Record<string, any>}
        } else if (sourceValue !== undefined) {
            // 其他属性直接覆盖
            ;(merged as any)[key] = sourceValue
        }
    })

    // 强制添加header
    if (!merged.headers) merged.headers = {}

    return merged as UniRequestInternalConfig
}

/**
 * 构建完整的URL
 * @param baseURL 基础URL
 * @param url 请求URL
 * @returns 完整URL
 */
export function buildURL(baseURL: string = '', url: string = ''): string {
    if (url.startsWith('http://') || url.startsWith('https://')) {
        return url
    }

    if (!baseURL) {
        return url
    }

    const normalizedBaseURL = baseURL.endsWith('/') ? baseURL.slice(0, -1) : baseURL
    const normalizedURL = url.startsWith('/') ? url : `/${url}`

    return `${normalizedBaseURL}${normalizedURL}`
}

/**
 * 构建查询字符串
 * @param params 参数对象
 * @returns 查询字符串
 */
export function buildQuery(params: Record<string, any>): string {
    if (!params || Object.keys(params).length === 0) {
        return ''
    }

    const query = Object.keys(params)
        .filter(key => params[key] !== undefined && params[key] !== null)
        .map(key => {
            const value = params[key]
            if (Array.isArray(value)) {
                return value.map(item => `${encodeURIComponent(key)}=${encodeURIComponent(item)}`).join('&')
            }
            return `${encodeURIComponent(key)}=${encodeURIComponent(value)}`
        })
        .join('&')

    return query ? `?${query}` : ''
}

/**
 * 构建完整的请求URL（包含查询参数）
 * @param config 请求配置
 * @returns 完整的URL
 */
export function buildFullURL(config: UniRequestConfig): string {
    let url = buildURL(config.baseURL, config.url) || ''

    if (config.params) {
        const query = buildQuery(config.params)
        url += query
    }

    return url
}

/**
 * 创建请求错误对象
 * @param message 错误消息
 * @param config 请求配置
 * @param code 错误码
 * @param request 请求对象
 * @param response 响应对象
 * @returns UniRequestError
 */
export function createError(
    message: string,
    config: UniRequestConfig,
    code?: string | number,
    request?: any,
    response?: any
): UniRequestError {
    const error = new Error(message) as UniRequestError
    error.config = config
    error.code = code
    error.request = request
    error.response = response
    return error
}

/**
 * 判断是否为取消错误
 * @param value 错误值
 * @returns 是否为取消错误
 */
export function isCancel(value: any): boolean {
    return value && value.__CANCEL__ === true
}

/**
 * 深拷贝对象
 * @param obj 要拷贝的对象
 * @returns 拷贝后的对象
 */
export function deepClone<T>(obj: T): T {
    if (obj === null || typeof obj !== 'object') {
        return obj
    }

    if (obj instanceof Date) {
        return new Date(obj.getTime()) as any
    }

    if (obj instanceof Array) {
        return obj.map(item => deepClone(item)) as any
    }

    if (typeof obj === 'object') {
        const cloned = {} as any
        for (const key in obj) {
            if (obj.hasOwnProperty(key)) {
                cloned[key] = deepClone(obj[key])
            }
        }
        return cloned
    }

    return obj
} 